//
//  FWWaterflowLayout.swift
//  DBS
//
//  Created by 王方伟 on 2017/4/20.
//  Copyright © 2017年 wfw. All rights reserved.
//

import UIKit

@objc protocol WaterflowLayoutDelegate : class {
    func waterflowLayout(_ waterflowLayout : FWWaterflowLayout, index : Int, itemWidth : CGFloat ) -> CGFloat
}

class FWWaterflowLayout: UICollectionViewFlowLayout {
    
    weak var delegate : WaterflowLayoutDelegate?
    var columnCount : Int = 3
    
    fileprivate lazy var attrsArray : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    fileprivate var columnHeights : [CGFloat] = [0]
    fileprivate var contentHeight : CGFloat = 0
    
    fileprivate var startIndex = 0
    
}

extension FWWaterflowLayout {
    override func prepare() {
        super.prepare()
        
        // 清除以前计算的所有高度
        columnHeights.removeAll()
        for _ in startIndex..<columnCount {
            columnHeights.append(sectionInset.top)
        }
        
         // 清除之前所有的布局属性
        attrsArray.removeAll()
        let count = collectionView?.numberOfItems(inSection: 0)
        for index in startIndex..<count! {
            let indexPath = IndexPath(item: index, section: 0)
            let attrs = layoutAttributesForItem(at: indexPath)
            attrsArray.append(attrs!)
        }
        
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attrsArray
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        let collectionViewW = collectionView?.frame.size.width
        let w = (collectionViewW! - sectionInset.left - sectionInset.right - CGFloat((columnCount - 1)) * minimumInteritemSpacing) / CGFloat(columnCount)
        
        let h = delegate?.waterflowLayout(self, index: indexPath.item, itemWidth: w)
        
        var destColumn : Int = 0
        var minColumnHeight = columnHeights.first!
        
        for index in 1..<columnCount {
            let columnHeight = columnHeights[index]
            if minColumnHeight > columnHeight {
                minColumnHeight = columnHeight
                destColumn = index;
            }
        }


        let x = sectionInset.left + CGFloat(destColumn) * (w + minimumInteritemSpacing)
        var y = minColumnHeight
        
        if y != sectionInset.top {
            y += minimumLineSpacing
        }
        attrs.frame = CGRect(x: x, y: y, width: w, height: h!)
        columnHeights[destColumn] = (attrs.frame.maxY)
        let columnHeight = columnHeights[destColumn]
        if contentHeight < columnHeight {
            contentHeight = columnHeight
        }
        return attrs
        
    }
    
    override var collectionViewContentSize: CGSize{
        return CGSize(width: 0, height: contentHeight + sectionInset.bottom)
    }
}
